import 'package:country_state_city/country_state_city.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/controllers/device/country/country_mdel.dart';
import 'package:share_fit/app/ute/uteped_const.dart';

import 'country_state.dart';

class CountryLogic extends BaseController {
  final CountryState state = CountryState();

  void onCountrySelected(Country country) {
    save("country_name", country.name, global: true);
    save("country_code", country.isoCode, global: true);
    var result = {"name": country.name, "code":country.isoCode};
    Get.back(result: result);
  }

  @override
  void onInit() {
    super.onInit();
    state.isLoading = true;
    getAllCountries().then((value) => _onGetCountries(value)
        .then((value) => _onCountiesFetchComplete(value)));
  }

  Future<List<CountryModel>> _onGetCountries(List<Country> countries) {
    List words = countries
        .map((e) => PinyinHelper.getFirstWordPinyin(e.name)
            .substring(0, 1)
            .toUpperCase())
        .toList();
    words.sort((a, b) => a.compareTo(b));
    final sortedSet = words.toSet();

    List<CountryModel> countriesList = [];
    for (var word in sortedSet) {
      var model = CountryModel(section: word, countries: []);
      for (var countryItem in countries) {
        var temp = PinyinHelper.getShortPinyin(countryItem.name)
            .substring(0, 1)
            .toUpperCase();
        if (word == temp) {
          model.getCountries.add(countryItem);
        }
      }
      countriesList.add(model);
    }

    return Future(() => countriesList);
  }

  void _onCountiesFetchComplete(List<CountryModel> countriesList) {
    state.countriesList.clear();
    state.countriesList.addAll(countriesList);
    state.isLoading = false;
    update(["loading_item", "list_view"]);
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void initState() {
    state.selectedCountryCode = read("country_code", defaultValue: "", global: true);
  }

  @override
  void onRemoteEvent(event, method) {
    // TODO: implement onRemoteEvent
  }
}
